package com.wans.guli.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.wans.guli.product.constant.em.AttrTypeEnum;
import com.wans.guli.product.entity.*;
import com.wans.guli.product.service.*;
import com.wans.guli.product.vo.AttrRespVO;
import com.wans.guli.product.vo.AttrRestVO;
import com.wans.guli.product.vo.AttrVO;
import com.wans.guli.product.vo.ProductAttrValueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicReference;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wans.guli.common.utils.PageUtils;
import com.wans.guli.common.utils.Query;

import com.wans.guli.product.dao.AttrDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
@SuppressWarnings("all")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByAttrId(Long catId, Map<String, Object> params, Integer arrType) {
        // 请求参数key获取
        String key = (String) params.get("key");
        // 请求参数key是否为空
        boolean empty = StringUtils.isEmpty(key);


        IPage<AttrEntity> page = this.lambdaQuery()
                .eq(catId != 0, AttrEntity::getCatelogId, catId)
                .eq(AttrEntity::getAttrType, arrType)
                .and(!empty, consumer ->
                        consumer.like(AttrEntity::getAttrId, key)
                                .or()
                                .like(AttrEntity::getAttrName, key)
                                .or()
                                .like(AttrEntity::getSearchType, key)
                                .or()
                                .like(AttrEntity::getValueType, key)
                ).page(new Query<AttrEntity>().getPage(params));

        List<AttrRespVO> attrRespVOS = BeanUtil.copyToList(page.getRecords(), AttrRespVO.class);
        AtomicReference<StringJoiner> builderName = new AtomicReference<>(new StringJoiner("/"));
        attrRespVOS.forEach(attrRespVO -> {
            getCatelogName(attrRespVO.getCatelogId(), builderName.get());
            attrRespVO.setCatelogName(builderName.toString());
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService
                    .lambdaQuery()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrRespVO.getAttrId())
                    .one();
            if (attrAttrgroupRelationEntity != null) {
                attrRespVO.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }

            builderName.set(new StringJoiner("/"));
        });
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrRespVOS);
        return pageUtils;
    }

    @Override
    public AttrEntity getInfoById(Long attrId) {
        // 用于存放分类路径
        LinkedList<Long> catelogPath = new LinkedList<>();

        AttrEntity attrEntity = this.getById(attrId);

        //TODO 获取分类路径 - 递归查询数据库 - 性能可能会差
        getCatelogPath(attrEntity.getCatelogId(), catelogPath);
        AttrVO attrVO = new AttrVO();
        // 属性转换
        BeanUtil.copyProperties(attrEntity, attrVO);
        // 设置属性分组id
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.lambdaQuery()
                .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId())
                .one();
        if (attrAttrgroupRelationEntity != null) {
            AttrGroupEntity attrGroupEntity = attrGroupService.lambdaQuery()
                    .eq(AttrGroupEntity::getAttrGroupId, attrAttrgroupRelationEntity.getAttrGroupId())
                    .one();
            if (attrGroupEntity != null) {
                attrVO.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            }
        }
        // 设置分类路径
        attrVO.setCatelogPath(catelogPath);

        return attrVO;
    }

    @Override
    @Transactional
    public void saveAttr(AttrRestVO attr) {
        // 清除前端传来的意外attrId
        attr.setAttrId(null);
        AttrEntity attrEntity = BeanUtil.copyProperties(attr, AttrEntity.class);
        boolean save = this.save(attrEntity);
        if (!save) throw new RuntimeException("保存失败");
        // 保存关联关系
        if (attr.getAttrType() == AttrTypeEnum.SALE.getCode()) return; // 忽略销售属性
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        boolean save2 = attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        if (!save2) throw new RuntimeException("保存失败");
    }

    @Override
    @Transactional
    public void updateAttrById(AttrRestVO attr) {
        // 校验防止为空
        if (attr.getAttrId() == null || attr.getAttrId() <= 0)
            throw new RuntimeException("参数错误");

        AttrEntity attrEntity = BeanUtil.copyProperties(attr, AttrEntity.class);
        boolean update = this.updateById(attrEntity);
        if (!update) throw new RuntimeException("更新失败");
        // 更新关联关系
        if (attr.getAttrType() == AttrTypeEnum.SALE.getCode()) return; // 忽略销售属性
        if (attr.getAttrGroupId() == null || attr.getAttrGroupId() <= 0) return;
        AttrAttrgroupRelationEntity oneAttrAttrgroupRelation = attrAttrgroupRelationService
                .lambdaQuery()
                .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId())
                .one();
        if (oneAttrAttrgroupRelation == null) throw new RuntimeException("更新失败");

        oneAttrAttrgroupRelation.setAttrGroupId(attr.getAttrGroupId());
        boolean save2 = attrAttrgroupRelationService.updateById(oneAttrAttrgroupRelation);
        if (!save2) throw new RuntimeException("保存失败");
    }

    @Override
    public List<ProductAttrValueEntity> queryAttr(Long spuId, Map<String, Object> params) {

        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.lambdaQuery()
                .eq(spuId != null, ProductAttrValueEntity::getSpuId, spuId).list();

        return attrValueEntities;
    }

    @Override
    @Transactional
    public void updateBatchProductAttrValueById(Long spuId, List<ProductAttrValueVO> productAttrValueVOList) {
        if (spuId == null || productAttrValueVOList == null || productAttrValueVOList.size() == 0)
            throw new RuntimeException("参数错误");

        productAttrValueVOList.forEach(productAttrValueVO -> {
            boolean updatedProductAttrValue = productAttrValueService.lambdaUpdate()
                    .set(ProductAttrValueEntity::getAttrName, productAttrValueVO.getAttrName())
                    .set(ProductAttrValueEntity::getAttrValue, productAttrValueVO.getAttrValue())
                    .eq(ProductAttrValueEntity::getSpuId, spuId)
                    .eq(ProductAttrValueEntity::getAttrId, productAttrValueVO.getAttrId())
                    .update();
            if (!updatedProductAttrValue)
                throw new RuntimeException("属性关系更新失败");
        });

    }


    /**
     * 递归查询分类路径
     *
     * @param catId       分类id
     * @param catelogPath 分类路径
     */
    private void getCatelogPath(Long catId, LinkedList<Long> catelogPath) {

        CategoryEntity category = categoryService.lambdaQuery().eq(CategoryEntity::getCatId, catId).one();
        if (category == null) return;
        if (category.getParentCid() != 0)
            getCatelogPath(category.getParentCid(), catelogPath);

        catelogPath.add(category.getCatId());

    }

    /**
     * 递归查询分类路径 - 名
     *
     * @param catId       分类id
     * @param catelogPath 分类路径
     */
    private void getCatelogName(Long catId, StringJoiner catelogName) {

        CategoryEntity category = categoryService.lambdaQuery().eq(CategoryEntity::getCatId, catId).one();
        if (category == null) return;
        if (category.getParentCid() != 0)
            getCatelogName(category.getParentCid(), catelogName);

        catelogName.add(category.getName());

    }


}